package cn.gwm.flink.streaming.dwm.charge.assist.gps;

import cn.gwm.flink.streaming.constant.BaseFields;
import cn.gwm.flink.streaming.dwm.charge.bean.ChargeArgs;
import cn.gwm.flink.streaming.dwm.charge.util.SupplyUtil;
import cn.gwm.utils.GpsBean;
import cn.gwm.utils.StreamUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONObject;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @ClassName CacheGpsMatch
 * @Description 缓存中 gps 匹配
 * @Author LiangGuang
 * @Date 2023/06/28 15:13
 */
public class CacheGpsMatch extends GpsMatch {
    @Override
    public void match(JSONObject summar, ChargeArgs args) throws Exception {
        if (super.getNext() != null) {
            super.getNext().match(summar, args);
        }
        // 判断是否需要进行匹配  --> 此处的条件可能会发生变化 ,再说
//        if (!summar.containsKey(BaseFields.LATITUDE) || BaseFields.defaultVal.equals(summar.getStr(BaseFields.LATITUDE))) {
        JSONObject nowdata = args.getRealNowData();
        List<List<String>> gpsList = new ArrayList<>();
        // 缓存数据
        Iterable<JSONObject> iterable = args.getListState().get();
        if (CollectionUtil.isNotEmpty(iterable)) {
            List<JSONObject> list = StreamUtil.convertIterable(iterable);
            list.forEach(item -> {
                if (!BaseFields.defaultVal.equals(item.getStr(BaseFields.LATITUDE)) && !BaseFields.defaultVal.equals(item.getStr(BaseFields.LONGITUDE))) {
                    gpsList.add(Arrays.asList(item.getStr(BaseFields.LATITUDE), item.getStr(BaseFields.LONGITUDE)));
                }
            });

        }
        // 再加上当前条
        if (!BaseFields.defaultVal.equals(nowdata.getStr(BaseFields.LATITUDE)) && !BaseFields.defaultVal.equals(BaseFields.LONGITUDE)) {
            gpsList.add(Arrays.asList(nowdata.getStr(BaseFields.LATITUDE), nowdata.getStr(BaseFields.LONGITUDE)));
        }
        if (gpsList.size() > 0) {
            GpsBean gpsBean = SupplyUtil.getCentroid(gpsList);
            if (gpsBean != null) {
                summar.set(BaseFields.LATITUDE, gpsBean.getWgLat());
                summar.set(BaseFields.LONGITUDE, gpsBean.getWgLon());
            }
        }
    }
//    }
}
